package com.fivec.javaproject.generatebitaddress.code.tools;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Iterator;
import java.util.List;

/**
 * @author wangyizhu
 * @version "1.8.0_131"
 * @email 2641956765@qq.com
 * @desc:
 * @Time 2021/12/07 9:02
 */
public class StaticMethod {
    /**
     * 仅填充带有前导0的十六进制字符串，因此总长度为64个字符
     */
    public static String adjustto64(String s) {
        switch (s.length()) {
            case 62:
                return "00" + s;
            case 63:
                return "0" + s;
            case 64:
                return s;
            default:
                throw new IllegalArgumentException("not a valid key: " + s);
        }
    }

    public static String bytestohex(byte[] bytes) {
        /**
         * 字节数组转16进制
         * @param bytes 需要转换的byte数组
         * @return 转换后的Hex字符串
         */
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static byte[] listTobytes(List<Byte> list) {
        /**
         * @param list
         * 将被转换为byte[]的List<Byte>
         * @return
         * 转换成的byte数组
         */
        if (list == null || list.size() < 0)
            return null;
        byte[] bytes = new byte[list.size()];
        int i = 0;
        Iterator<Byte> iterator = list.iterator();
        while (iterator.hasNext()) {
            bytes[i] = iterator.next();
            i++;
        }
        return bytes;
    }

    public static byte[] getHash256(byte[] pubKey) {
        /**
         * 该方法用于将传入字符串进行sha256计算返回string
         */
        byte[] s = new byte[0];
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            s = sha.digest(pubKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return s;
    }

    public static byte[] getRipemd160(byte[] pubKey){
        /**
         * 该方法用于将传入byte[]进行Ripemd160计算并返回byte[]
         */
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        MessageDigest rmd = null;
        try {
            rmd = MessageDigest.getInstance("ripemd160", "BC");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        byte[] r1 = rmd.digest(pubKey);
        return r1;
    }
}
